package edu.iastate.mis438.mealtime;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TabHost;
import android.widget.TextView;

public class Recipes extends Activity implements OnClickListener{

	String pageNumber = "0";
	String recipeType = "";
	TextView tv;
	TextView tv1;
	TextView tv2;
	TextView tv3;
	TextView tv4;
	TextView tv5;
	ArrayList<String> resultsList = new ArrayList<String>();
	ArrayList<String> descList = new ArrayList<String>();
	private static String key = "9a6ae1fceea24f2894fba9311bfe20db";
	private static String secret = "549aeee4d7ec46198bd88e89986b38a1";
	private static final String HMAC_SHA1 = "HmacSHA1";
	private static final String ENC = "UTF-8";
	private static Base64 base64 = new Base64();
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		//requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); 
        setContentView(R.layout.recipes);
        
        tv = (TextView)findViewById(R.id.tvTest);
        
        TabHost tabs=(TabHost)findViewById(android.R.id.tabhost);
		
		tabs.setup();
		
		TabHost.TabSpec spec=tabs.newTabSpec("tag1");
		
		spec.setContent(R.id.tab1);
		spec.setIndicator("Breakfast");
		tabs.addTab(spec);
	
		spec=tabs.newTabSpec("tag2");
		spec.setContent(R.id.tab2);
		spec.setIndicator("Lunch");
		tabs.addTab(spec);	
		
		spec=tabs.newTabSpec("tag3");
		spec.setContent(R.id.tab3);
		spec.setIndicator("Dinner");
		tabs.addTab(spec);
	}
	
	private class SearchLookupTask extends AsyncTask<String, Void, String[]>{
		
		@Override
		protected String[] doInBackground(String... params) {
			String[] query = params;
			String searchTerm = query[0];
			try{
				List<NameValuePair> qparams = new ArrayList<NameValuePair>();
				// These params should ordered in key

				// qparams.add(new BasicNameValuePair("food_id", "33691"));
				qparams.add(new BasicNameValuePair("max_results", "5"));
				qparams.add(new BasicNameValuePair("oauth_consumer_key", key));
				qparams.add(new BasicNameValuePair("oauth_nonce", "" + (int) (Math.random() * 100000000)));
				qparams.add(new BasicNameValuePair("oauth_signature_method", "HMAC-SHA1"));
				qparams.add(new BasicNameValuePair("oauth_timestamp", "" + (System.currentTimeMillis())));
				qparams.add(new BasicNameValuePair("oauth_version", "1.0"));
				qparams.add(new BasicNameValuePair("page_number", pageNumber));
				qparams.add(new BasicNameValuePair("method", "recipes.search"));
				qparams.add(new BasicNameValuePair("recipe_type", recipeType));
				//qparams.add(new BasicNameValuePair("search_expression", searchTerm));

				// generate the oauth_signature
				String signature = getSignature(URLEncoder.encode(
						"http://platform.fatsecret.com/rest/server.api", ENC),
						URLEncoder.encode(URLEncodedUtils.format(qparams, ENC), ENC));

				// add it to params list
				qparams.add(new BasicNameValuePair("oauth_signature", signature));

				// generate URI which lead to access_token and token_secret.
				URI uri = URIUtils.createURI("http", "platform.fatsecret.com", -1, "/rest/server.api", URLEncodedUtils.format(qparams, ENC), null);

				URL website = new URL(uri.toString());

				SAXParserFactory spf = SAXParserFactory.newInstance();
				SAXParser sp = spf.newSAXParser();
				XMLReader xr = sp.getXMLReader();
				RecipeXMLHandler handler = new RecipeXMLHandler();
				xr.setContentHandler(handler);
				xr.parse(new InputSource(website.openStream()));
				String[] information = handler.getRecipeNameInformation();
				String[] descriptions = handler.getRecipeDescriptions();
				for(int i = 0; i < information.length; i++){
					resultsList.add(information[i]);
					descList.add(descriptions[i]);
				}
				return information;
			}catch (Exception e){
				tv.setText("error");
			}

			return null;
		}


		@Override
		protected void onPostExecute(String[] result) {
			tv1.setText(result[0].toString());
			tv2.setText(result[1].toString());
			tv3.setText(result[2].toString());
			tv4.setText(result[3].toString());
			tv5.setText(result[4].toString());
		}


		private String getSignature(String url, String params)
				throws UnsupportedEncodingException, NoSuchAlgorithmException,
				InvalidKeyException {
			/**
			 * base has three parts, they are connected by "&": 1) protocol 2) URL
			 * (need to be URLEncoded) 3) Parameter List (need to be URLEncoded).
			 */
			StringBuilder base = new StringBuilder();
			base.append("GET&");
			base.append(url);
			base.append("&");
			base.append(params);
			// yea, don't ask me why, it is needed to append a "&" to the end of
			// secret key.
			byte[] keyBytes = (secret + "&").getBytes(ENC);

			SecretKey key = new SecretKeySpec(keyBytes, HMAC_SHA1);

			Mac mac = Mac.getInstance(HMAC_SHA1);
			mac.init(key);

			// encode it, base64 it, change it to string and return.
			return new String(base64.encode(mac.doFinal(base.toString().getBytes(
					ENC))), ENC).trim();
		}

}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		SearchLookupTask task = new SearchLookupTask();
		switch(v.getId()){
		case R.id.tab1:
			recipeType = "breakfast";
			task.execute(recipeType);
			tv.setText(resultsList.get(0));
			break;
		case R.id.tab2:
			recipeType = "lunch";
			task.execute(recipeType);
			break;
		case R.id.tab3:
			recipeType = "dinner";
			task.execute(recipeType);
			break;
		}
	}

}
